home *** CD-ROM | disk | FTP | other *** search
- Path: noc.tor.hookup.net!news
- From: Richard Steadman <rsteadma@micromedia.on.ca>
- Newsgroups: comp.lang.c
- Subject: Problem with realloc()
- Date: Mon, 04 Mar 1996 19:38:39 -0500
- Organization: Micromedia
- Message-ID: <313B8D0F.3109@micromedia.on.ca>
- NNTP-Posting-Host: keeper.mmltd.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (Win95; I)
-
- I wonder if anyone can spot the problem in the following code.
- The function readfile() is supposed to read a text file, and
- assign each line of it to a dynamic array. It has worked correctly
- for some files, but recently when realloc() is called, it causes a
- Bus error and core dump. I have no idea why. I have added a couple
- of printf() statements to pinpoint the problem, and it is
- definitely in the call to realloc().
-
- Here's the code:
-
- #include <stdio.h>
- #include <stdlib.h>
-
- #define MINLINES 10 /* allocate storage for at least ? lines */
- #define MAXLINELEN 1000
-
- char **readfile(char *filename, int *size, int charsperline,
- long maxfsize)
- {
- register int asize=0;
- long fsize=0;
- FILE *fp;
- char **array;
- char **newarray;
- long lines;
- char *memarea;
- int linelen;
-
- if ( (fp=fopen(filename,"r"))==NULL) return NULL;
-
- fseek(fp,0L,SEEK_END);
- fsize=ftell(fp); /* get file length */
- fseek(fp,0L,SEEK_SET);
-
- if (fsize>maxfsize) return NULL;
-
- /* guess at number of lines: realloc later if nec. */
- lines=fsize/charsperline;
-
- if (lines<MINLINES) lines=MINLINES;
-
- if ( (memarea=(char *) malloc(fsize+1) )==NULL)
- /* +1 for \0 in last read */
- return(NULL);
-
- if ( (array=malloc((size_t)(lines * sizeof(char *))) )==NULL){
- free(memarea);
- return(NULL);
- }
-
- array[0]=memarea;
-
- while (fgets(array[asize],MAXLINELEN,fp)!=NULL){
-
- printf("fgets ok\n"); fflush(stdout);
- linelen=strlen(array[asize]);
- array[asize][linelen-1]='\0';
- if (asize >= lines){
- lines+=lines/2; /* increase by 50% */
- printf("reallocating\n"); fflush(stdout);
- if ( (newarray=realloc(array,
- (size_t)(lines*sizeof(char *))))==NULL){
- free(memarea);
- free(array);
- return NULL;
- }
- printf("done reallocating\n"); fflush(stdout);
- array=newarray;
- }
- array[asize+1]=array[asize]+linelen;
- asize++;
- printf("EOL\n"); fflush(stdout);
- }
-
- *size=asize;
- return array;
- }
-